#pragma once
#include<iostream>
#include<string>
#include<sys/ipc.h>
#include<sys/shm.h>
const std::string gpath = "/home/weiliang/lesson/lesson26/sharemem";
int gprojId = 0x6666;
int gshmsize = 4096;
mode_t gmode = 0600;
class ShareMemory
{
private:
 void CreateShmHelper(int shmflg)
    {
        _key = ::ftok(gpath.c_str(),gprojId);
        std::cout << "ftok key: " << _key << std::endl;
        if(_key < 0)
        {
            std::cerr<<"ftok error"<<std::endl;
            return;
        }
        _shmid = ::shmget(_key,gshmsize,shmflg);
        if(_shmid < 0)
        {
             std::cerr<<"shmid error"<<std::endl;
            return;

        }
        std::cout<<"shmid: "<<_shmid<<std::endl;
    }
public:
    ShareMemory()
    :_shmid(-1)
    ,_key(0)
    ,_addr(nullptr)
    {}
    ~ShareMemory()
    {}
   
    void CreateShm()
    {
        CreateShmHelper(IPC_CREAT | IPC_EXCL | gmode);
    }
    void Getshm()
    {
        CreateShmHelper(IPC_CREAT);
    }
    void AttachShm()
    {
        _addr = shmat(_shmid,nullptr,0);
        if((long long)_addr == -1)
        {
            std::cout<<"attach error "<<std::endl;
        }
    }
    void DetachShm()
    {
        ::shmdt(_addr);
        std::cout<<"detach done: "<<std::endl;
    }
    void DleteShm()
    {
        shmctl(_shmid,IPC_RMID,nullptr);
    }
    void *GetAddr()
    {
        return _addr;
    }
    void ShmMete()
    {}
private:
    int _shmid;
    key_t _key;
    void *_addr;
};
ShareMemory shm;

struct data
{
    char status[32];
    char lasttime[48];
    char image[4000];
};